import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutterhello/api/api.dart';
import 'package:flutterhello/controller/Controller.dart';
import 'package:flutterhello/my_app.dart';
import 'package:flutterhello/util/host_util.dart';
import 'package:flutterhello/widgets/loading_dialog.dart';
import 'package:flutterhello/widgets/my_toast.dart';
import 'package:flutterhello/widgets/tips_card.dart';
import 'package:get/get.dart' as MyGet;
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:photo_view/photo_view.dart';
import 'package:fluttertoast/fluttertoast.dart';

class AddActPage extends StatefulWidget {
  @override
  _AddActPageState createState() => _AddActPageState();
}

class _AddActPageState extends State<AddActPage> {
  GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
  List<Asset> images = [];
  String title = "";
  String content = "";
  String _error;

  Future<void> loadAssets() async {
    List<Asset> resultList;
    String error;

    try {
      resultList = await MultiImagePicker.pickImages(
        maxImages: 9,
        enableCamera: true,
      );
    } on Exception catch (e) {
      error = e.toString();
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      images = images + resultList;
      if (error == null) _error = 'No Error Dectected';
      print(_error);
    });
  }

  Widget buildGridView1() {
    if (images.length == 0)
      return GridView.count(
          crossAxisCount: 3,
          children: List.generate(1, (index) {
            print("fuck");
            return Container(
              height: 120,
              width: 120,
              decoration: BoxDecoration(
                border: Border(
                    left: BorderSide(width: 1, color: Colors.black26),
                    right: BorderSide(width: 1, color: Colors.black26),
                    bottom: BorderSide(width: 1, color: Colors.black26),
                    top: BorderSide(width: 1, color: Colors.black26)),
                borderRadius: BorderRadius.circular(5),
              ),
              child: IconButton(
                icon: Icon(Icons.add),
                onPressed: loadAssets,
              ),
            );
          }));
    else
      return GridView.count(
        crossAxisCount: 3,
        crossAxisSpacing: 10,
        mainAxisSpacing: 10,
        children: List.generate(images.length + 1, (index) {
          if (index < images.length) {
            Asset asset = images[index];
            return Container(
              width: 300,
              height: 300,
              child: Stack(
                children: [
                  Align(
                    alignment: Alignment(0, 0),
                    child: AssetThumb(
                      asset: asset,
                      width: 300,
                      height: 300,
                    ),
                  ),
                  Align(
                    alignment: Alignment(0.9, -0.9),
                    child: GestureDetector(
                      child: Icon(
                        const IconData(0xe600, fontFamily: "alIcons"),
                        size: 15,
                        color: Colors.blueGrey,
                      ),
                      onTap: () {
                        setState(() {
                          this.images.removeAt(index);
                        });
                      },
                    ),
                  )
                ],
              ),
            );
          } else {
            return Container(
              height: 120,
              width: 120,
              decoration: BoxDecoration(
                border: Border(
                    left: BorderSide(width: 1, color: Colors.black26),
                    right: BorderSide(width: 1, color: Colors.black26),
                    bottom: BorderSide(width: 1, color: Colors.black26),
                    top: BorderSide(width: 1, color: Colors.black26)),
                borderRadius: BorderRadius.circular(5),
              ),
              child: IconButton(
                icon: Icon(Icons.add),
                onPressed: loadAssets,
              ),
            );
          }
        }),
      );
  }

  int type = 1;
  var choseTeam = null;
  @override
  Widget build(BuildContext _context) {
    final controller = MyGet.Get.put(Controller());
    return Scaffold(
      appBar: PreferredSize(
        child: AppBar(
          title: Text('发起活动'),
          centerTitle: true,
        ),
        preferredSize: Size.fromHeight(50),
      ),
      body: Container(
        margin: EdgeInsets.all(10),
        child: Column(
          children: <Widget>[
            Expanded(
              child: Column(
                children: <Widget>[
                  TextField(
                    cursorColor: Colors.black87,
                    cursorWidth: 0.5,
                    maxLines: 1,
                    style: TextStyle(color: Colors.black54, fontSize: 16),
                    scrollPadding: EdgeInsets.all(0),
                    decoration: InputDecoration(
                      contentPadding: EdgeInsets.all(0),
                      hintText: '标题',
                      hintStyle: TextStyle(fontSize: 14, color: Colors.black38),
                      border: InputBorder.none,
                    ),
                    onChanged: (value) {
                      this.title = value;
                    },
                  ),
                  Container(
                    height: 100,
                    width: double.infinity,
                    child: TextFormField(
                      cursorColor: Colors.black87,
                      cursorWidth: 0.5,
                      maxLines: 7,
                      style: TextStyle(color: Colors.black54, fontSize: 16),
                      scrollPadding: EdgeInsets.all(0),
                      decoration: InputDecoration(
                          contentPadding: EdgeInsets.all(0),
                          hintText: '输入活动说明',
                          hintStyle:
                              TextStyle(fontSize: 14, color: Colors.black26),
                          border: InputBorder.none),
                      onChanged: (val) {
                        this.content = val;
                      },
                    ),
                  ),
                  Container(
                    width: double.infinity,
                    height: 50,
                    decoration: BoxDecoration(
                      border: Border(
                          top: BorderSide(color: Colors.black26),
                          bottom: BorderSide(color: Colors.black26)),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Text('发起形式:'),
                        SizedBox(
                          width: 20,
                        ),
                        Row(
                          children: [
                            Text("团队"),
                            Radio(
                              value: 1,
                              focusColor: Colors.blueGrey,
                              activeColor: Colors.blueGrey,
                              groupValue: this.type,
                              onChanged: (value) {
                                setState(() {
                                  this.type = value;
                                });
                              },
                            ),
                          ],
                        ),
                        Row(
                          children: [
                            Text("个人"),
                            Radio(
                              value: 2,
                              groupValue: this.type,
                              focusColor: Colors.blueGrey,
                              activeColor: Colors.blueGrey,
                              onChanged: (value) {
                                setState(() {
                                  this.type = value;
                                });
                              },
                            ),
                          ],
                        )
                      ],
                    ),
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  this.type == 1
                      ? GestureDetector(
                          child: this.choseTeam == null
                              ? Container(
                                  width: double.infinity,
                                  height: 50,
                                  decoration: BoxDecoration(
                                    border: Border(
                                        top: BorderSide(color: Colors.black26),
                                        bottom:
                                            BorderSide(color: Colors.black26)),
                                  ),
                                  child: Row(
                                    children: [
                                      Text(
                                        '选择团队',
                                        style: TextStyle(color: Colors.black45),
                                      ),
                                    ],
                                  ),
                                )
                              : TipsCard(
                                  favicon: HostUtil.getHost() +
                                      this.choseTeam['favicon'],
                                  name: this.choseTeam['groupname'],
                                ),
                          onTap: () {
                            showModalBottomSheet<void>(
                              context: context,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.only(
                                  topLeft: Radius.circular(20),
                                  topRight: Radius.circular(20),
                                ),
                              ),
                              builder: (BuildContext context) {
                                return EasyRefresh.custom(
                                  slivers: <Widget>[
                                    SliverToBoxAdapter(
                                      child: SizedBox(
                                        height: 20,
                                      ),
                                    ),
                                    SliverList(
                                      delegate: SliverChildBuilderDelegate(
                                        (context, index) {
                                          return Padding(
                                            padding: EdgeInsets.only(
                                              left: 20,
                                              right: 20,
                                            ),
                                            child: Column(
                                              children: [
                                                SizedBox(
                                                  height: 10,
                                                ),
                                                GestureDetector(
                                                  child: TipsCard(
                                                    favicon: HostUtil
                                                            .getHost() +
                                                        controller
                                                                .myCreateGroup[
                                                            index]['favicon'],
                                                    name: controller
                                                            .myCreateGroup[
                                                        index]['groupname'],
                                                  ),
                                                  onTap: () {
                                                    this.choseTeam = controller
                                                        .myCreateGroup[index];
                                                    Navigator.of(context).pop();
                                                    setState(() {});
                                                  },
                                                ),
                                              ],
                                            ),
                                          );
                                        },
                                        childCount:
                                            controller.myCreateGroup.length,
                                      ),
                                    )
                                  ],
                                );
                              },
                            );
                          },
                        )
                      : Container(),
                  Expanded(
                    child: Padding(
                      padding: EdgeInsets.only(top: 10),
                      child: buildGridView1(),
                    ),
                  ),
                  Align(
                    alignment: Alignment(0.8, 0),
                    child: GestureDetector(
                      child: Container(
                        height: 50,
                        width: double.infinity,
                        decoration: BoxDecoration(
                          color: Colors.blueGrey,
                          borderRadius: BorderRadius.all(Radius.circular(5)),
                        ),
                        child: Center(
                          child: Text(
                            '提 交',
                            style: TextStyle(color: Colors.white, fontSize: 20),
                          ),
                        ),
                      ),
                      onTap: () async {
                        var result = await showDialog(
                          context: _context,
                          builder: (context) {
                            return AlertDialog(
                              title: Text('提示'),
                              content: Text('确认发布吗？'),
                              actions: <Widget>[
                                TextButton(
                                  child: Text('取消'),
                                  onPressed: () {
                                    Navigator.of(context).pop('cancel');
                                  },
                                ),
                                TextButton(
                                  child: Text('确认'),
                                  onPressed: () {
                                    if (this.type == 1) {
                                      // 是团队
                                      if (title != "" &&
                                          content != "" &&
                                          choseTeam != null &&
                                          images.length != 0) {
                                        submit(
                                            images,
                                            title,
                                            content,
                                            'group',
                                            choseTeam['createUser'],
                                            choseTeam['id'],
                                            _context);
                                      } else {
                                        MyTost.showTost('参数不完整');
                                      }
                                    } else {
                                      // 是个人
                                      if (title != "" &&
                                          content != "" &&
                                          images.length != 0) {
                                        submit(
                                            images,
                                            title,
                                            content,
                                            'user',
                                            controller.userInfo['id'],
                                            "",
                                            _context);
                                      } else {
                                        MyTost.showTost('参数不完整');
                                      }
                                    }
                                  },
                                ),
                              ],
                            );
                          },
                        );
                        print('$result');
                      },
                    ),
                  )
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

submit(images, title, content, fromType, userID, groupID, context) async {
  showDialog(
    context: context,
    barrierDismissible: false,
    builder: (BuildContext context) {
      return new LoadingDialog(
        text: "上传中…",
      );
    },
  );
  FormData formData = new FormData.fromMap({});
  for (int i = 0; i < images.length; i++) {
    ByteData byteData = await images[i].getByteData();
    List<int> imageData = byteData.buffer.asUint8List();
    MultipartFile multipartFile = MultipartFile.fromBytes(
      imageData,
      filename: images[i].name,
    );
    formData.files.addAll([
      MapEntry("file", multipartFile),
    ]);
  }
  var res = await Api.uploadImg(formData);
  if (res['code'] == 1000) {
    var res2 = await Api.createActivite({
      "title": title,
      "content": content,
      "fromType": fromType,
      "userID": userID,
      "groupID": groupID,
      "images": res['data'],
    });
    if (res2['code'] == 1000) {
      Navigator.of(context).pop();
      MyTost.showTost(res2['message']);
      MyGet.Get.offAll(MyApp());
    }
  } else {
    MyTost.showTost('上传失败');
    Navigator.of(context).pop();
  }
}
